<?php

namespace App\Console\Commands;

use App\Models\Admin\AdminTender;
use App\Models\Admin\AdminTenderKeyword;
use App\Models\Admin\AdminTenderSite;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use QL\QueryList;

class TenderCollect extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:tender';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'make tender collect';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
//        DB::beginTransaction();
        try {
            //获取关键词
            $keywords=AdminTenderKeyword::pluck('name')->toArray();
            //获取到要抓取信息的网站
            $sites=AdminTenderSite::get()->toArray();
            if(!empty($keywords) && !empty($sites))
            {
                $time=time();
                foreach ($sites as $v) {
                    foreach ($keywords as $kw)
                    {
                        $url=$v['url'];
                        if($v['name']=='中国政府采购网')
                        {
                            $today=date('Y:m:d');
                            $url.="$kw&start_time=$today&end_time=$today";
                            $ql=QueryList::get($url);
                            // 元数据采集规则
                            $rules = [
                                'title'=>['a:eq(0)','text'],
                                'url' => ['a','href'],
                            ];
                            // 切片选择器
                            $range = '.vT-srch-result-list-bid>li';
                        }
                        elseif ($v['name']=='中国招标网')
                        {
                            $request_data=[
                                'searchtype'=>'zb',
                                'attachment'=>'',
                                'queryword'=>$kw,
                                'field'=>'all',
                                'provinces'=>'',
                                'channels'=>'bidding',
                                'maxPages'=>50,
                                'leftday'=>1,
                                'currentpage'=>1,
                            ];
                            $ql=QueryList::post($url,$request_data);
                            // 元数据采集规则
                            $rules = [
                                'title'=>['td:eq(1)>a>span','text'],
                                'url' => ['td:eq(1)>a','href'],
                            ];
                            // 切片选择器
                            $range = '#datatbody>tr';
                        }
                        elseif ($v['name']=='中国招标采购导航网')
                        {
                            $request_data=[
                                'page'=>1,
                                'search-time-typ'=>1,
                                'city-all'=>'all',
                                'result-keyword-or-form'=>$kw,
                                'result-infotype-input[]'=>'bn',
                            ];
                            $ql=QueryList::post($url,$request_data);
                            // 元数据采集规则
                            $rules = [
                                'title'=>['ul>#titles>a','title'],
                                'url'=>['ul>#titles>a','rec_link'],
                            ];
                            // 切片选择器
                            $range = '#get_content>.dingyue_list_cons';
                        }
//                        elseif ($v['name']=='全国公共资源交易平台')
//                        {
//                            $today=date('Y-m-d');
//                            $today_9=date('Y-m-d',$time-86400*9);
//                            $request_data=[
//                                'TIMEBEGIN_SHOW'=>$today_9,
//                                'TIMEBEGIN'=>$today_9,
//                                'TIMEEND_SHOW'=>$today,
//                                'TIMEEND'=>$today,
//                                'SOURCE_TYPE'=>'1',
//                                'DEAL_TIME'=>'01',
//                                'DEAL_CLASSIFY'=>'00',
//                                'DEAL_STAGE'=>'0001',
//                                'DEAL_PROVINCE'=>'0',
//                                'DEAL_CITY'=>'0',
//                                'DEAL_PLATFORM'=>'0',
//                                'BID_PLATFORM'=>'0',
//                                'DEAL_TRADE'=>'0',
//                                'isShowAll'=>'1',
//                                'PAGENUMBER'=>'1',
//                                'FINDTXT'=>$kw,
//                            ];
////                            $header=['Content-Type: application/x-www-form-urlencoded; charset=UTF-8'];
//                            $ql=zc_curl($url,'POST',$request_data);
////                            dd($ql);
////                            if($kw=='食材')
////                            {
////                                dd($ql)->find('body')->text();
////                            }
//                        }

                        elseif ($v['name']=='中国招标投标公共服务平台')
                        {
                            $today=date('Y-m-d');
                            $signDate=date('Y-m-d H:i:s');
                            $url.="$kw&startcheckDate=$today&endcheckDate=$today&signDate=$signDate&searchDate=$today";
                            $ql=QueryList::get($url);
                            // 元数据采集规则
                            $rules = [
                                'title'=>['td:eq(0)>a','title'],
                                'url' => ['td:eq(0)>a','href'],
                            ];
                            // 切片选择器
                            $range = 'tr:gt(0)';
                        }

                        if(!empty($ql))
                        {
                            if($v['name']=='全国公共资源交易平台')
                            {

                            }
                            else
                            {
                                $res = $ql->rules($rules)->range($range)->queryData();
                            }
                        }

//                        if($v['name']=='中国招标投标公共服务平台' && $kw=='水果')
//                        {
//                            dd($res);
//                        }

                        //插入数据库，要判断标题是否存在
                        if(!empty($res))
                        {
                            $res_col=collect($res);
                            $title_res=$res_col->pluck('title');
                            $yesterday=$time-86400;
                            $titles_db=AdminTender::whereIn('title',$title_res)->where('created_at','>',$yesterday)->pluck('title')->toArray();
                            foreach ($res as $ke=> &$va)
                            {
                                if(in_array($va['title'],$titles_db))
                                {
                                    unset($res[$ke]);
                                }
                                else
                                {
                                    $va['site_id']=$v['id'];
                                    $va['created_at']=$time;
                                    $va['updated_at']=$time;
                                    if($v['name']=='中国招标采购导航网')
                                    {
                                        $va['url']='http://m.okcis.cn'.$va['url'];
                                    }
                                    elseif($v['name']=='中国招标投标公共服务平台')
                                    {
                                        $va['url']=substr($va['url'],20,-2);
                                    }

                                }
                            }
//                            if($v['name']=='中国招标投标公共服务平台' && $kw=='食材')
//                            {
//                                dd($res);
//                            }
                            if(!empty($res))
                            {
                                DB::table('admin_tender')->insert($res);
                            }
                        }
                    }
                }
            }
//            DB::commit();
        }
        catch (\Exception $exception)
        {
//            DB::rollBack();
//            print_r($exception->getMessage());
            Log::info('make tender error '.$exception->getMessage());
        }
    }

}
